<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.keywords" placeholder="搜索名称"/>
            </a-form-item>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form-item label="状态">
              <a-select v-model="queryParam.status" placeholder="请选择"
                        allowClear >
                <a-select-option value="1">进行中</a-select-option>
                <a-select-option value="3">未开始</a-select-option>
                <a-select-option value="4">已结束</a-select-option>
                <a-select-option value="2">已下架</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="!advanced && 6 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item @click="setAllStatus(1)" key="1"><a-icon type="upload" />上架</a-menu-item>
          <a-menu-item @click="setAllStatus(2)" key="2"><a-icon type="download" />下架</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="title1" slot-scope="text,record">
        <div style="margin-bottom: 10px;">{{record.name}} {{record.names.join(',')}}</div>
        <div>
          <div >
            <a-badge status="success" v-if="record.status==1" text="进行中" />
            <a-badge status="processing" v-else-if="record.status==3" text="未开始" />
            <a-badge status="default" v-else-if="record.status==4" text="已结束" />
            <a-badge status="default" v-else text="已下架" />
          </div>
        </div>
      </span>
      <span slot="timeRange" slot-scope="text,record">
        <template >
        <div>
          开始:{{record.time_start|timeFormat}}<br/>
          结束:{{record.time_end|timeFormat}}
        </div>
          </template>
      </span>
      <span slot="orderCount" slot-scope="text,record">
        <template >
        <div>
          {{record.student_ids.length}}
        </div>
        </template>
      </span>
      <span slot="action" slot-scope="text,record">
        <template >
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <!--<a @click="handleUserManage(record)">领取记录</a>-->
          <!--<a-divider type="vertical" />-->
          <a-popconfirm title="删除后不可恢复,确定删除吗?" @confirm="deleteHandle(record)"  okText="确定" cancelText="取消">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </span>
    </s-table>
    <a-modal
            title="操作"
            :width="1000"
            style="top: 20px;"
            :bodyStyle="{maxHeight:'500px','overflowY':'scroll'}"
            v-model="visible"
            @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="名称类型"
                  hasFeedback
          >
            <a-radio-group :disabled="formData.id>0" v-model="formData.name_type" buttonStyle="solid">
              <a-radio-button :value="1">固定</a-radio-button>
              <a-radio-button :value="2">随机</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item
                  v-show="formData.name_type==1"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="名称"
                  hasFeedback
          >
            <a-input  :disabled="formData.id>0" v-decorator="[
          'name',
          {rules: [ ]}
        ]"
                     placeholder="请输入考试名称"/>
          </a-form-item>
          <a-form-item
                  v-show="formData.name_type==2"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="名称(多个)"
                  hasFeedback
          >
            <a-select  :disabled="formData.id>0"
                    mode="tags"
                    placeholder="请输入多个名称,回车隔开"
                    v-model="formData.names"
            >
            </a-select>

          </a-form-item>


          <a-form-item
                  v-show="!formData.id"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="版本"
                  hasFeedback
          >
            <a-select @change="versionChange" v-model="formData.version_id" placeholder="请选择"
                      allowClear >
              <a-select-option v-for="(version,index) in subjectTree" :value="version.id" :key="index">{{version.name}}</a-select-option>
            </a-select>

          </a-form-item>
          <a-form-item
                  v-show="!formData.id"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="学科"
                  hasFeedback
          >
            <a-select @change="subjectChange"  v-model="formData.subject_id" placeholder="请选择"
                      allowClear >
              <a-select-option v-for="(subject,index) in subjectOptions" :value="subject.id" :key="index">{{subject.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
                  label="所属知识点"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
          >
            <a-tree-select
                    v-decorator="[
                  'cate_ids',
                  {rules: [{ required: true, message: '请输入所属知识点' }]}
                ]"
                    style=" width: 90% ; margin-right: 10px; "
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    :treeData="cateOptions"
                    multiple
                    allowClear
                    treeNodeFilterProp="title"
                    placeholder='请选择所属知识点'
                    treeDefaultExpandAll
                    v-model="formData.cate_ids"
            >
            </a-tree-select>
            <a-popover content="请选择所属知识点,支持多选">
              <a-icon type="question-circle" />
            </a-popover>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="考试时间"
                  hasFeedback
          >
            <a-range-picker
                    v-model="formData.time_range_moment"
                    :showTime="{
        defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
      }"
                    format="YYYY-MM-DD HH:mm:ss"
            />
          </a-form-item>


          <a-form-item
                  label="学生"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
          >
            <a-select
                    :disabled="formData.id>0"
                    optionFilterProp="title"
                    mode="multiple"
                    v-model="formData.student_ids"
                    placeholder="选择学生"
            >
              <a-select-option :key="option.id" v-for="option in studentOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="演示视频"
                  hasFeedback
          >
            <a-input  v-decorator="[
          'demo_url',
          {rules: [ ]}
        ]"
                      placeholder="请输入演示视频网址"/>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="状态"
                  hasFeedback
          >
            <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="上架" unCheckedChildren="下架" />
          </a-form-item>
        </a-form>


      </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>


    <a-modal
            title="订单记录"
            :width="1000"
            style="top: 20px;"
            :bodyStyle="{maxHeight:'500px','overflowY':'scroll'}"
            v-model="userVisible"
            @ok="userVisible=false"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">
          <a-table :columns="userColumns" :dataSource="guafenUserList" :pagination="userPagination"
                   @change="handleUserTableChange"
                   rowKey="id" :scroll="{ y: 300 }" bordered>
            <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm }" class='custom-filter-dropdown'>
              <a-input
                      v-model="userQuery.keywords"
                      placeholder="搜索用户名/手机号"
                      style="width: 188px; margin-bottom: 8px; display: block;"
              />
              <a-button
                      type='primary'
                      @click="userSearch(selectedKeys, confirm)"
                      icon="search"
                      size="small"
                      style="width: 90px; margin-right: 8px"
              >搜索</a-button>
              <a-button
                      @click="userSearchReset(selectedKeys, confirm)"
                      size="small"
                      style="width: 90px"
              >重置</a-button>
            </div>
            <span slot="name" slot-scope="text,record">
              {{record.user_name}}
            </span>
            <span slot="member_count" slot-scope="text,record">
              {{record.member_count}}
            </span>
            <span slot="pen_price" slot-scope="text,record">
              {{record.pen_price|price}}
            </span>
            <span slot="status" slot-scope="text,record">
            <a-badge status="processing" v-if="record.status==1" text="进行中" />
            <a-badge status="success" v-else-if="record.status==2" text="完成" />
            <a-badge status="error" v-else-if="record.status==3" text="过期失败" />
            </span>
            <span slot="time_start" slot-scope="text,record">
            开始:{{record.time_start|timeFormat}}<br/>
            结束:{{record.time_end|timeFormat}}
            </span>
          </a-table>
        </a-form>
      </a-spin>
    </a-modal>

  </a-card>
</template>

<script>
  import STable from '@/components/table/'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  import AInput from 'ant-design-vue/es/input/Input'
  import EditableCell from '@/components/EditableCell/'
  import RSwitch from '@/components/RSwitch/'
  import PicUploader from '@/components/PicUploader/'
  import moment from 'moment'
  import 'moment/locale/zh-cn';
  moment.locale('zh-cn');
  import { cateTreeList,exameList,exameAdd,exameEdit,exameDelete,exameDetail,videoList,videoAdd,videoEdit,videoDelete,videoDetail ,studentOptions  } from '@/api/exame';
  import { getSubjectTree    } from '@/api/subject';
  export default {
    name: 'ExameList',
    components: {
      AInput,
      ATextarea,
      STable,
      EditableCell,
      RSwitch,
      PicUploader
    },
    data () {
      return {
        visible: false,
        saveLoading:false,
        userVisible:false,
        formData:{
          id:'',
          name_type: 1,
          name: '',
          names: [],
          cate_ids:[],
          student_ids:[],
          class_ids:[],
          time_range:[],
          time_range_moment:[],
          demo_url:'',
          status: 1
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        form: this.$form.createForm(this),
        mdl: {},

        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
          keywords:'',
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: 'id',
            width: '50px'
          },
          {
            title: '标题',
            dataIndex: 'title',
            scopedSlots: { customRender: 'title1' },
          },
          {
            width:'250px',
            title: '考试时间',
            dataIndex: 'time_start',
            scopedSlots: { customRender: 'timeRange' },
          },
          {
            title: '学生数',
            width:'150px',
            dataIndex: 'order_count',
            scopedSlots: { customRender: 'orderCount' },
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '180px',
            scopedSlots: { customRender: 'action' },
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          console.log('loadData');
          console.log(this.queryParam);
          this.queryParam = Object.assign(parameter, this.queryParam);
          return exameList(this.queryParam)
            .then(res => {
              console.log('res');
              return res.data
            })
        },

        selectedRowKeys: [],
        selectedRows: [],
        cateOptions:[],
        subjectTree:[

        ],
        subjectOptions:[],
        goodsOptions:[],
        youhuiquanOptions:[],
        //领取人员表头
        userColumns: [
        {
          title: '#',
          dataIndex: 'id',
          width: '100px'
        },
        {
          title: '发起人',
          dataIndex: 'user_name',
          width:'150px',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'name',
          }
        },
        {
          title: '人数',
          width:'100px',
          dataIndex: 'member_count',
          scopedSlots: {
            customRender: 'member_count',
          },
        },
        {
          title: '状态',
          width:'100px',
          dataIndex: 'status',
          scopedSlots: {
            customRender: 'status',
          },
          filters: [
            {
              text: '进行中',
              value: '1'
            },
            {
              text: '完成',
              value: '2'
            },
            {
              text: '过期失败',
              value: '3'
            }],
          filterMultiple:false,
        },
        {
          title: '时间',
          width:'150px',
          dataIndex: 'time_start',
          scopedSlots: {
            customRender: 'time_start',
          },
        },
      ],
        userPagination:{
      },
      userQuery:{
        guafenquan_id:0,
        status:0,
        page:1,
        keywords:undefined
      },
        studentOptions:[],
      guafenUserList:[]
      }
    },
    computed: {
    },
    created(){
    },
    mounted(){
      let that = this;
      that.getSubjectTreeOptions();
      that.getStudentOptions();
    },
    methods: {
      moment,
      handleCancel(){
        this.visible = false
      },
      getSubjectTreeOptions(){
        let that = this;
        getSubjectTree().then(res => {
          that.subjectTree =  res.data
        })
      },
      versionChange(version_id){
        let that = this;
        console.log('versionChange',version_id);
        let currentVersion = that.subjectTree.filter(item =>{
          return item.id == version_id
        });
        console.log('currentVersion',currentVersion);
        that.subjectOptions =  currentVersion[0].children;
        that.formData.subject_id = undefined;
      },
      subjectChange(){
        this.formData.cate_ids = [];
        this.getCateOptions();
      },
      // 增
      handleAdd() {
        console.log('moment.locale()')
        console.log(moment.locale());
        let that = this;
        this.visible = true;
        this.form.resetFields();
        this.formData = {
          id:'',
          name_type: 1,
          name: '',
          names: [],
          cate_ids:[],
          student_ids:[],
          class_ids:[],
          time_range:[],
          time_range_moment:[],
          demo_url:'',
          status: 1
        };
        setTimeout( () =>{
          that.form.setFieldsValue({ ...this.formData });
        });
      },
      // 改
      handleEdit(record) {
        let self = this
        exameDetail({ id: record.id }).then(res => {
          setTimeout(()=>{
            self.form.setFieldsValue({ ...res.data })
          },1)
//          self.formData = {...res.data};
          self.formData = Object.assign(self.formData, res.data) //尼玛 日期选择器有bug 必须这样赋值
          self.formData.id = res.data.id;
          self.formData.time_range_moment = [moment(res.data.time_start*1000),moment(res.data.time_end*1000)];
          self.getCateOptions();
        })
        this.visible = true
      },

      // 增改 处理
      handleOk(e) {
        let self = this;
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
            if(self.formData.name_type==1){
              if(!values.name){
                self.$message.error('请输入实验名称');
                return ;
              }
            }else{
              if(self.formData.names.length==0){
                self.$message.error('请输入并且选择实验名称');
                return ;
              }
            }
            if(self.formData.cate_ids.length==0){
              self.$message.error('请至少选择一个知识点');
              return ;
            }
            if(self.formData.time_range_moment.length!=2){
              self.$message.error('请选择时间范围');
              return ;
            }
            if(self.formData.student_ids.length==0){
              self.$message.error('请至少学生一名学生');
              return ;
            }
            console.log('Received values of form: ', values)
            console.log('Received valuess of formData: ', self.formData)
            self.saveLoading = true;
            let formData = {
              id:self.formData.id,
              name_type:self.formData.name_type,
              name: values.name,
              names:self.formData.names,
              demo_url:values.demo_url,
              cate_ids:self.formData.cate_ids,
              subject_id:self.formData.subject_id,
              version_id:self.formData.version_id,
              student_ids:self.formData.student_ids,
              class_ids:self.formData.class_ids,
              time_range:[self.formData.time_range_moment[0].format('YYYY-MM-DD HH:mm:ss'),self.formData.time_range_moment[1].format('YYYY-MM-DD HH:mm:ss')],
              status:self.formData.status,
            };
            if(self.formData.id) {
              exameEdit(formData).then(res => {
                self.$message.success('修改成功')
                self.$refs.table.refresh(true)
                self.visible = false;
                self.saveLoading = false;
              }).catch(err =>{
                self.$message.error(err.data.msg);
                self.saveLoading = false;
              })
            }else{
              exameAdd(formData).then(res => {
                self.$message.success('新增成功')
                self.$refs.table.refresh(true)
                self.visible = false
                self.saveLoading = false;
              }).catch(err =>{
                self.$message.error(err.data.msg);
                self.saveLoading = false;
              })
            }
          }
        })
      },
    // 查
    onSearch() {
      let self = this;
      self.$refs.table.refresh(true)
    },
      setAllStatus(status){
        let self = this;
        setGuafenAllStatus({
          ids:self.selectedRowKeys,
          status:status,
        })
                .then(res => {
                  self.$message.success('设置成功')
                  self.$refs.table.refresh(true)
                })
      },
     // 删
      deleteHandle(record) {
        let self = this
        exameDelete({ id: record.id }).then(res => {
          self.$message.success('删除成功')
          self.$refs.table.refresh(true)
      }).catch(err =>{
          self.$message.error(err.data.msg)
        })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      getCateOptions(){
        let that = this;
        cateTreeList({
          subject_id: that.formData.subject_id
        })
                .then(res => {
                  that.cateOptions =  res.data;
                })
      },
      getStudentOptions(){
        let that = this;
        studentOptions()
                .then(res => {
                  res.data.map(item =>{
                    item.id =  item.id+'';
                  })
                  that.studentOptions =  res.data;
                })
      },
    handleUserManage(record) {
        let self = this
        self.userQuery.guafenquan_id = record.id;
        self.userQuery.keywords = undefined;
        self.userQuery.status = undefined;
        self.userPagination.page = 1;
        self.fetchUserList();
        this.userVisible = true
      },

      fetchUserList(){
        let self = this
        getGuafenUserList(Object.assign(self.userQuery,self.userPagination)).then(res => {
          self.guafenUserList = res.data.list
          self.userPagination.total = res.data.total
        })
      },

      userSearch(selectedKeys,confirm){
        let self = this
        confirm();
        self.fetchUserList();
      },
      userSearchReset(selectedKeys,confirm){
        let self = this;
        confirm();
        self.userQuery.keywords = undefined;
        self.fetchUserList();
      },
      handleUserTableChange(pagination, filters, sorter) {
        console.log('filters',filters);
        let that = this;
        if(filters.status){
          that.userQuery.status = filters.status[0];
        }else{
          that.userQuery.status = 0;
        }
        const pager = { ...this.pagination };
        pager.current = pagination.current;
        that.pagination = pager;
        that.userQuery.page = pagination.current;
        that.fetchUserList();
      },

    },
    watch: {
      /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
    }
  }
</script>


<style scoped>
  .custom-filter-dropdown {
    padding: 8px;
    border-radius: 4px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, .15);
  }

  .highlight {
    background-color: rgb(255, 192, 105);
    padding: 0px;
  }
</style>